#include "message_processor.h"
#include "../proto/mmo.pb.h"
#include "../proto/message.pb.h"
#include <iostream>

void MessageProcessor::register_handler(uint32_t msg_type, 
                                       std::function<void(const google::protobuf::Message&, std::shared_ptr<Connection>)> handler) {
    handlers_[msg_type] = handler;
}

void MessageProcessor::process(const char* data, size_t length, uint32_t msg_type, std::shared_ptr<Connection> connection) {
    auto it = handlers_.find(msg_type);
    if (it != handlers_.end()) {
        google::protobuf::Message* message = nullptr;
        switch (msg_type) {
            case 1: // 登录请求
                message = new mmo::LoginRequest();  // 使用mmo::命名空间
                break;
            default:
                std::cerr << "Unsupported message type: " << msg_type << std::endl;
                return;
        }

        if (message->ParseFromArray(data, length)) {
            it->second(*message, connection);
        } else {
            std::cerr << "Failed to parse message of type: " << msg_type << std::endl;
        }
        delete message;  // 释放内存
    } else {
        std::cerr << "No handler registered for message type: " << msg_type << std::endl;
    }
}